package com.dkm.orproject.dkmoa.action.flow;

import com.alibaba.fastjson.JSONObject;
import com.dkm.orproject.dkmoa.domain.OaEntryFlow;
import com.dkm.orproject.dkmoa.domain.OaJurisdiction;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.service.flow.OaEntryFlowService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName : OaEntryFlowAction  //类名
 * @Description : 人事流程Action  //描述
 * @Author : 易嵘  //作者
 * @Date: 2020-08-04 16:24  //时间
 */
@RestController
@RequestMapping("oaEntryFlowAction")
public class OaEntryFlowAction {

    /**
     * 人事流程Service
     */
    @Resource
    OaEntryFlowService entryFlowService;

    @Resource
    Tools tools;

    /**
     * 分页查询
     *
     * @param entryFlow 入职流程模型 用于条件查询
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param page      当前页数
     * @param limit     显示的行数
     * @return 查询结果集
     */
    @GetMapping("findAll")
    @UserLoginToken
    public Map<String, Object> findAll(OaEntryFlow entryFlow,
                                       String startTime,
                                       String endTime,
                                       Integer page,
                                       Integer limit,
                                       HttpServletRequest request) {
        OaPersonnel personnel = (OaPersonnel) request.getSession().getAttribute("user");
        List<OaJurisdiction> button = (List<OaJurisdiction>) request.getSession().getAttribute("button");//当前登陆人id
        Long personnelId = personnel.getPkPersonnelId();
        for (OaJurisdiction jurisdiction : button) {
            //判断如果拥有查看权限则查询所有
            if ("ENTRY_SHOW".equals(jurisdiction.getJurisdictionCode())) {
                personnelId = null;
                break;
            }
        }
        try {

            //查询集合
            List<OaEntryFlow> entryFlowList = entryFlowService.findAll(entryFlow, startTime, endTime, page, limit, personnelId);
            //总行数
            Long rowCount = entryFlowService.rowCount(entryFlow, startTime, endTime, personnelId);
            return Tools.maps(entryFlowList, rowCount);
        } catch (Exception e) {
            Map<String, Object> map = new HashMap<>(16);
            e.printStackTrace();
            OaLog log = new OaLog();
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(e.getLocalizedMessage());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogTitle("入职流程分页查询");
            log.setLogType("0");
            return tools.errorMap(map, log);
        }
    }

    /**
     * 新增一个空的入职流程
     *
     * @return 返回id
     */
    @UserLoginToken
    @GetMapping("addEntryFlow")
    public OaEntryFlow addEntryFlow(HttpServletRequest request) {
        return entryFlowService.addEntryFlow(request);
    }

    /**
     * 起草提交
     *
     * @param entryFlow 入职流程模型 用于前台接收数据
     * @param request   服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("audit")
    public Map<String, Object> audit(OaEntryFlow entryFlow, HttpServletRequest request) {
        //回调Map
        Map<String, Object> map = new HashMap<>(16);
        //获取登陆人信息
        OaPersonnel personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //为空则返回
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        //新建日志模型
        OaLog log = new OaLog();
        log.setLogTitle("入职流程提交");
        log.setCreatedBy(personnel.getPersonnelName());
        log.setLogIp(request.getRemoteAddr());
        try {
            int row = entryFlowService.audit(entryFlow, personnel);
            log.setLogBody(JSONObject.toJSON(entryFlow).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            e.printStackTrace();
            log.setLogBody(e.getLocalizedMessage());
            log.setLogType("0");
            tools.errorMap(map, log);
        }
        return map;
    }

    /**
     * 审核通过
     *
     * @param entryFlow  流程模型
     * @param formReason 通过原因
     * @param request    服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("auditPass")
    public Map<String, Object> auditPass(OaEntryFlow entryFlow, String formReason, HttpServletRequest request) {
        //回调Map
        Map<String, Object> map = new HashMap<>(16);
        //获取登陆人信息
        OaPersonnel personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //为空则返回
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        //新建日志模型
        OaLog log = new OaLog();
        try {
            int row = entryFlowService.auditPass(entryFlow, formReason, personnel);
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(entryFlow).toString());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogType("1");
            log.setLogTitle("入职流程新增或修改");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(e.getLocalizedMessage());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogType("0");
            tools.errorMap(map, log);
        }
        return map;
    }

    /**
     * 审核不通过
     *
     * @param entryFlow  流程模型
     * @param formReason 审核原因
     * @param request    服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("auditNoPass")
    public Map<String, Object> auditNoPass(OaEntryFlow entryFlow, String formReason, HttpServletRequest request) {
        //回调Map
        Map<String, Object> map = new HashMap<>(16);
        //获取登陆人信息
        OaPersonnel personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //为空则返回
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        //新建日志模型
        OaLog log = new OaLog();
        try {
            int row = entryFlowService.auditNoPass(entryFlow, formReason, personnel);
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(entryFlow).toString());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogType("1");
            log.setLogTitle("入职流程新增或修改");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(e.getLocalizedMessage());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogType("0");
            tools.errorMap(map, log);
        }
        return map;
    }


    /**
     * 批量删除
     *
     * @param ids     入职流程id集
     * @param request 服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @DeleteMapping("deleteAll")
    public Map<String, Object> deleteAll(@RequestParam(value = "ids[]", required = false) Long[] ids, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(16);
        //获取登陆人信息
        OaPersonnel personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //为空则返回
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        OaLog log = new OaLog();
        int row;
        try {
            List<Long> list = Arrays.asList(ids);
            List<OaEntryFlow> entryFlows = entryFlowService.selectAll(list);
            row = entryFlowService.deleteAll(list);
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(entryFlows).toString());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogType("1");
            log.setLogTitle("入职流程删除");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(e.getLocalizedMessage());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogType("0");
            tools.errorMap(map, log);
        }
        return map;
    }

    /**
     * 暂存数据
     *
     * @param entryFlow
     * @param request
     * @return
     */
    @UserLoginToken
    @PostMapping("addTemporary")
    public Map<String, Object> addTemporary(OaEntryFlow entryFlow, HttpServletRequest request) {
        //回调Map
        Map<String, Object> map = new HashMap<>(16);
        //获取登陆人信息
        OaPersonnel personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //为空则返回
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        //新建日志模型
        OaLog log = new OaLog();
        try {
            int row = entryFlowService.addTemporary(entryFlow, personnel);
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(entryFlow).toString());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogType("1");
            log.setLogTitle("入职流程新增或修改");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            e.printStackTrace();
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(e.getLocalizedMessage());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogType("0");
            tools.errorMap(map, log);
        }
        return map;
    }

    /**
     * id查询
     * @param id
     * @param request
     * @return
     */
    @UserLoginToken
    @GetMapping("findById/{id}")
    public OaEntryFlow findById(@PathVariable("id") Long id, HttpServletRequest request) {
        try {
            return entryFlowService.findById(id);
        } catch (Exception e) {
            Map<String, Object> map = new HashMap<>(16);
            e.printStackTrace();
            OaPersonnel personnel = (OaPersonnel) request.getSession().getAttribute("user");
            OaLog log = new OaLog();
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(e.getLocalizedMessage());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogTitle("入职流程分页查询");
            log.setLogType("0");
            tools.errorMap(map, log);
            return null;
        }
    }

    /**
     * id删除
     *
     * @param id      入职流程id
     * @param request 服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @DeleteMapping("deleteById/{id}")
    public Map<String, Object> deleteById(@PathVariable("id") Long id, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(16);
        //获取登陆人信息
        OaPersonnel personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //为空则返回
        if (ObjectUtils.isEmpty(personnel)) {
            return tools.rowMap(map, 0, null);
        }
        OaLog log = new OaLog();
        int row;
        try {
            OaEntryFlow entryFlow = entryFlowService.findById(id);
            row = entryFlowService.deleteById(id);
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(entryFlow).toString());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogType("1");
            log.setLogTitle("入职流程删除");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(e.getLocalizedMessage());
            log.setCreatedBy(personnel.getPersonnelName());
            log.setLogType("0");
            tools.errorMap(map, log);
        }
        return map;
    }

    /**
     * 根据当前登陆人查询入职信息
     * @param request 服务器请求 用于得到当前登陆人信息
     * @return 入职流程信息
     */
    @UserLoginToken
    @GetMapping("findByPersonnelId")
    public OaEntryFlow findByPersonnelId(HttpServletRequest request){
        OaPersonnel personnel= (OaPersonnel) request.getSession().getAttribute("user");
        return entryFlowService.findByPersonnelId(personnel.getPkPersonnelId());
    }

    @UserLoginToken
    @GetMapping("getThisRecord")
    public Long getThisRecord(HttpServletRequest request){
        OaPersonnel personnel= (OaPersonnel) request.getSession().getAttribute("user");
        return entryFlowService.getThisRecord(personnel.getPkPersonnelId());
    }

    /**
     * 日期格式化
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}
